<?php

namespace App\Trip\Plane\Variflight;

class Token
{
    private string $appid;
    private string $appsecurity;
    private array  $params;

    public function __construct(string $appid, string $appsecurity, array $params)
    {
        $this->appid       = $appid;
        $this->appsecurity = $appsecurity;
        $this->params      = $params;
    }

    public function getParamString(): string
    {
        $params          = $this->getParams();
        $params['token'] = $this->getToken();
        return $this->buildParamString($params);
    }

    private function getParams(): array
    {
        $params          = $this->params;
        $params['appid'] = $this->appid;
        return $params;
    }

    private function getToken(): string
    {
        $param        = $this->getParams();
        $param_string = $this->buildParamString($param);
        return strtolower(md5(md5($param_string.$this->appsecurity)));
    }

    public function buildParamString(array $param): string
    {
        // 排序
        ksort($param);
        // 拼接
        $params = [];
        foreach ($param as $key => $value) {
            $params[$key] = "{$key}={$value}";
        }
        return implode("&", $params);
    }
}